/* --------------------------------------------------------------------------
 * jvc.data version 2.0.1
 *  (c) 2011 Shenzhen jvc Software Co., Ltd.
 *
 *  数据表格 by rufujian @ 2011.08.24
 *
 * -------------------------------------------------------------------------- */
if( ! jvc.data)
jvc.data = new  jvc_data();

function jvc_data()
{
	
   this.querySingle=function (jsrc, frm, name)
   {
 
      var json = new jvc_json();
      if( ! name)name = "res";
      json.query(jsrc, function(j, name, frm)
      {
         if( ! j)return;
         var results = j[name];
         jvc.data.setFirst(frm, results);
      }
      , name, frm);


   }
  
   this.query=function(jsrc, callback,p1,p2,p3,p4){
   		new jvc_json().query(jsrc, callback,p1,p2,p3,p4);
   	}
	this.query2=function(jsrc, listDiv, pageDiv,name){		
		if(!name)name="res";
		 this.appendNodeMessage(listDiv,"<nobr>&nbsp;&nbsp;查询中,请稍候...</nobr>");
		 new jvc_json().query(jsrc, json_callback, name, listDiv, pageDiv, jsrc);
		}	
	this.submit=function(frm,callback,p1,p2,p3,p4){	
   	 	var json = new jvc_json();
      var jsrc = json.buildQueryString(frm);   
      json.query(jsrc, callback,p1,p2,p3,p4);
      
	}
	this.callback=function(j,frm,listDiv,pageDiv,name){
		if(!name)name="res";
		var json = new jvc_json();
		  var jsrc = json.buildQueryString(frm); 
		  json_callback(j, name, listDiv, pageDiv, jsrc);
	}
   this.submit2 = function(frm,  listDiv, pageDiv,isLoadPage,name)
   {   	   
         if(listDiv.isQuery=="1")return;
   
     listDiv.isQuery="1";
   	 if(!listDiv.isGrid)this.appendNodeMessage(listDiv,"<nobr>&nbsp;&nbsp;查询中,请稍候...</nobr>");
      var json = new jvc_json();
      var jsrc = json.buildQueryString(frm);   
      if(!name)name="res";
      var newJsrc=jsrc;
      if(isLoadPage && pageDiv.me && pageDiv.me.pageinfo){
      	newJsrc+="&"+name+".curpage="+pageDiv.me.pageinfo.CurPage;
      }
      json.query(newJsrc, json_callback, name, listDiv, pageDiv, jsrc);

   }

   this.appendNodeMessage=function(oTable,message){
        for(var i = oTable.childNodes.length - 1; i >= 1;
      i -- )
      {
         if(oTable.childNodes[i].jvcCreate && oTable.childNodes[i].jvcMessage)
         {
            oTable.removeChild(oTable.childNodes[i]);
         }
      }
   if(oTable.tagName=="TBODY"){
	   	var newTR=document.createElement("tr");
	   	var newTD=document.createElement("td");
	   	newTR.appendChild(newTD);
	   	newTD.style.padding = "10px";
	   	newTD.innerHTML=message;
	   	newTR.jvcCreate=true;
	    newTR.jvcMessage=true;	
		oTable.insertBefore(newTR, newTR.nextSibling);
	} else{
		var newTR=document.createElement("div");
	   	newTR.style.padding = "10px";
	   	newTR.innerHTML=message;
	   	newTR.jvcCreate=true;
	   	newTR.jvcMessage=true;
		oTable.insertBefore(newTR, newTR.nextSibling);
	}  
   }	
   this.appendNode=function(oTable,result,index){
        var obj=result[index];
   	 	if(oTable.childNodes.length == 0)return;
   	 	var nCount=0;
   	  for(var i = 0; i < oTable.childNodes.length;      i ++ )
      {
         if(!oTable.childNodes[i].jvcCreate)nCount++;else break;
      }
       for(var ii = 0; ii < nCount; ii ++ )
         {

            var newTR = oTable.childNodes[ii].cloneNode(true);
            if(newTR.tagName=="TR"){
                    if(index % 2==1){
                    	newTR.className="list_two";
                    	jvc.attachEvent(newTR, "mouseout", jvc_data_setclass(newTR, 'list_two'));
                	}else{
                		newTR.className="list_one";
                		jvc.attachEvent(newTR, "mouseout", jvc_data_setclass(newTR, 'list_one'));                		
                	}
                	
               		jvc.attachEvent(newTR, "mouseover", jvc_data_setclass(newTR, 'list_move'));
            	
          	}

            newTR.jvcCreate = true;
            if(newTR.nodeType == 3)continue;
            if(newTR.style)	newTR.style.display = "";
            if(newTR.id){newTR.id = (replacehref(newTR.id, obj));}
            oTable.appendChild(newTR);
            this.replaceCell(newTR, obj, i + 1);
            this.replacefld(newTR, obj, i + 1);
         }
   	}

   this.setList = function (oTable, j, name)
   {
         if(!name)name="res";
   
   	if(oTable.isGrid){
   		this.setGrid(oTable,j[name],oTable.defaultData);
   		return;
   	}
   	 if(!oTable)return;
   	  if(!oTable.childNodes)return;
      if(oTable.childNodes.length == 0)return;
    
      this.node = oTable.childNodes[0];
      if(this.node.style)this.node.style.display = "none";
      for(var i = oTable.childNodes.length - 1; i >= 1;
      i -- )
      {
         if(oTable.childNodes[i].jvcCreate)
         {
            oTable.removeChild(oTable.childNodes[i]);
         }
      }
      if( ! j)return;
      var result = j[name];
      if( ! result){      
      this.appendNodeMessage(oTable,"<nobr>&nbsp;&nbsp;抱歉,查询结果无数据！</nobr>");
      return;}
      var nCount = oTable.childNodes.length;
      for(var i = 0; i < result.length; i ++ )
      {
      	
      	this.appendNode(oTable,result,i);
        
      }


   }
   this.setFirst = function (oTable, results)
   {
      var value;
      if(results && results.length > 0)value = 	results[0];
      this.findFld(oTable);
      this.setFld(oTable);      
      if( ! value){this.initFldValue();return;}
      jvc.data.setSingle(oTable, value);
      this.initFldValue();

   }

this.setGrid = function (oTable, results,defaultValue)
   {
     if(defaultValue)jvc.data.setSingle(oTable, defaultValue);
     if(!results)return;
      this.findFld(oTable);
      this.setFld(oTable);
     for(var i=0;i<results.length;i++){
      var value = results[i];
      value.jvc_fld_index=i+1;
      jvc.data.setSingle(oTable, value);
      }
    this.initFldValue();
   }

   this.setSingle = function (oTable, value)
   {
      for(var i = 0; i < oTable.childNodes.length;
      i ++ )
      {

         this.replaceCell(oTable.childNodes[i], value);
         this.replacefld(oTable.childNodes[i], value);
      }

   }

   this.setSelect = function(obj, result)
   {
      if( ! obj.oldLen)
      {
         obj.oldLen = 	obj.options.length;
         if(obj.options.length == 0)return;         
         var op = obj.options[obj.oldLen - 1];
         if(!op)return;
         obj.valuefld = op.value;
         if(op.id)obj.id = op.id;
         if(op.getAttribute("namefld"))obj.namefld = op.getAttribute("namefld");
         if(op.getAttribute("valuefld"))obj.valuefld = op.getAttribute("valuefld");
      }

      obj.options.length = obj.oldLen - 1;
      if( ! result)return;
      for(var i = 0; i < result.length; i ++ )
      {
         var value = result[i][obj.valuefld.toLowerCase()];
         var name = result[i][obj.namefld.toLowerCase()];
         var opt = new Option(name, value);
         if(obj.jvalue && obj.jvalue == value)opt.selected = true;
         if(obj.id)opt.id = replacehref(obj.id, result[i], i);
         obj.options[obj.oldLen - 1 + i] = opt;
      }
      var jload = obj.getAttribute("onloadj");
      if(jload)
      {
         this.onloadj(obj, jload);
         obj.onchange = function()
         {
            try
            {eval(jload);}
            catch(e)
            {}
         }
      }
   }
   this.initFldValue = function()
   {
      if( ! this.RegistEventObj)return;
      for(var i = 0; i < this.RegistEventObj.length;
      i ++ )
      {
         this.changeObjValue(this.RegistEventObj[i].obj,this.RegistEventObj[i] );
      }

   }
   this.setFld = function(cell)
   {

      if(cell.nodeType == 3)return;
      var fld = cell.getAttribute('fld');
      var varParten = /^(\w){1,100}$/;
      var sEvalEvents = "";
      if( ! varParten.test(fld))
      {
      	if(!cell.getAttribute('enabled'))cell.disabled = true;
         for(var i = 0; i < this.fields.length; i ++ )
         {
         	
            var regexpField = new RegExp(this.fields[i], "gi");
            var findField = regexpField.exec(fld);
            if( ! findField)continue;
            var ext = [];
            ext[0] = "module";
            ext[1] = "ext";
            
            for(var j = 0; j < ext.length; j ++ )
            {
               var obj ;
               if(!jvc.notIE)obj= document.getElementById(ext[j] + "." + findField);
               else 
                	obj=$$(ext[j] + "." + findField);
               if( ! obj)continue;
               var  RegistEventObj = this.getRegistEventObj(obj);
               sEvalEvents += "var " + findField + "=autoTypeValue($$('"+ext[j]+"."+findField+"').value);";
               var ChangeFldObj = this.getChangeFldObj(RegistEventObj, cell);
               ChangeFldObj.findField = findField;
               ChangeFldObj.ext = [j];
            }

         }
         if(sEvalEvents != "")
         {
            cell.sEvalEvents = sEvalEvents;

         }
      }
      for(var i = 0; i < cell.childNodes.length;
      i ++ )
      {
         this.setFld(cell.childNodes[i]);
      }
   }
   this.getChangeFldObj = function (eventObj, cell)
   {
      for(var i = 0; i < eventObj.changeFld.length;
      i ++ )
      {
         if(eventObj.changeFld[i].obj == cell)return eventObj.changeFld[i];
      }
      var newChangeFldObj = new Object();
      newChangeFldObj.obj = cell;
      eventObj.changeFld[eventObj.changeFld.length] = newChangeFldObj;
      return newChangeFldObj;
   }
   this.getRegistEventObj = function(obj)
   {
      if( ! this.RegistEventObj)this.RegistEventObj = [];
      for(var i = 0; i < this.RegistEventObj.length;
      i ++ )
      {
         if(this.RegistEventObj[i].obj == obj)return this.RegistEventObj[i];
      }

      newRegistEventObj = new Object();
      this.RegistEventObj[this.RegistEventObj.length] = newRegistEventObj;
      newRegistEventObj.obj = obj;
      newRegistEventObj.changeFld = [];
      var me = this;
      jvc.attachEvent(obj, "propertychange", function()
      {
         me.changeObjValue(obj,newRegistEventObj);

      }
      );
      return newRegistEventObj;
   }

   this.changeObjValue = function(obj,RegistEventObj)
   {
   	
      if(!RegistEventObj) RegistEventObj = this.getRegistEventObj(obj);
      var dblParten = /^[-\+]?\d+(\.\d+)?$/;
      for(var i = 0; i < RegistEventObj.changeFld.length;
      i ++ )
      {
         var changeFld = RegistEventObj.changeFld[i];
         var sEvalEvents = changeFld.obj.sEvalEvents;
         var fld = changeFld.obj.getAttribute("fld")
         var tempValue = eval(sEvalEvents + fld);
         if(tempValue == Infinity || isNaN(tempValue))tempValue = 0;
         if(dblParten.test(tempValue))tempValue = decimal(tempValue, 2);
         changeFld.obj.value = 	tempValue;
         this.changeObjValue(changeFld.obj);

      }

   }
   this.findFld = function(cell)
   {
      if( ! this.fields)this.fields = [];
      if(cell.nodeType == 3)return;
      var fld = cell.getAttribute('fld');
      if(fld == "@")fld = cell.name;      
      var varParten = /^(\w){1,100}$/;
      var fieldIndex = this.fields.length;
      if(varParten.test(fld))
      {
         if(fld)	this.fields[fieldIndex] = fld;
      }
      else
      {
         var name = cell.name;
         if(name.indexOf(".") > 0)
         {
            var names = name.split(".");
            name = names[names.length - 1];
         }
         this.fields[fieldIndex] = name;

      }
      for(var i = 0; i < cell.childNodes.length;
      i ++ )
      {
         this.findFld(cell.childNodes[i]);
      }

   }
   this.onloadj = function(me, jload)
   {
   	
      try
      {
         if( ! jload)return;
         this.me = me;
         eval(jload);
      }
      catch(err)
      {
         alert(err);
      }
   }
   this.replaceCell = function(cell, resultf)
   {
   	
      if(cell.nodeType == 3)return;
 	  //专门给setGrid用
 	  if(resultf.jvc_fld_index && resultf.jvc_fld_index!=cell.getAttribute('fld_index'))return;
      var fld = cell.getAttribute('fld');
      cell.jdata = resultf;
      if(cell.type == "radio" || cell.type == "checkbox"){
    	  if(cell.value  && cell.value.indexOf('@')==0)cell.value = (replacehref(cell.value, resultf));
      }
    	if(cell.tagName=="IMG"){
    		var jsrc=cell.getAttribute('jsrc');
      	 	if(jsrc){
      	 		cell.src = replacehref(jsrc, resultf);
      	 		return;
      	 	}
    	}
    
      if(fld)
      {

         var jdata = resultf;

         var varParten = /^(\w){1,100}$/;
         var intParten = /^[-\+]?\d+$/;
         var dblParten = /^[-\+]?\d+(\.\d+)?$/;
         var RegistEventObj = [];
         //if( ! varParten.test(fld))return;
         fld = fld.toLowerCase();
         var value = "";

           if(fld.indexOf("(")>-1){
											var fields=[];
											var sEval="";
											for(var tmp_fld in resultf) fields[fields.length]=tmp_fld ; 
											for(var i=0;i<fields.length;i++){
												sEval+="var "+fields[i]+"=jdata."+fields[i]+";";
											}	
											try{
											value=eval(sEval+fld);
										}catch(err){
											}
										}else if(resultf)value = resultf[fld];
         if(value == undefined)value = "";
         if(cell.getAttribute("fmt"))value = format(value, cell.getAttribute("fmt"));
         if(cell.type == "radio")
         {
            alert(cell.value);
            cell.checked = (cell.value == value);
         }
         else if(cell.type == "select-one" || cell.type == "select" )
         {
            cell.jvalue = value;
            for(var i = 0; i < cell.options.length; i ++ )
            {
               if(cell.options[i].value == value)
               {
                  cell.options[i].selected = true;
                  return;
               }
            }

         }
         else if(cell.type == "checkbox")
         {
            cell.checked = (cell.value == value);
         }
         else  if(cell.type == "text" || cell.type == "hidden"  || cell.type == "textarea")
         {

            cell.value = value;
         }
 		else  if(cell.type == "file")
         {

            cell.value = value;
         }
         else if(cell.tagName.toLowerCase()=="img"){
           cell.src =value;
         }
         else
         {
         	try{
            if(cell.innerText)cell.innerText = value;
            else cell.innerHTML = value;
          }catch(err){
          	 alert("errorType"+cell.type );
          	}
         }

      }
      if(cell.jsrc)
      {

         cell.src = replacehref(cell.jsrc, resultf);
      }
      if(cell.jhref)cell.href = (replacehref(cell.jhref, resultf));
      if(cell.id && cell.id.indexOf('@') != - 1)cell.id = (replacehref(cell.id, resultf));
      if(cell.name && cell.name.indexOf('@') != - 1)cell.name = (replacehref(cell.name, resultf));
      if(cell.title && cell.title.indexOf('@') != - 1)cell.title = (replacehref(cell.title, resultf));
      if(cell.href && cell.href.indexOf('@') != - 1)cell.href = (replacehref(cell.href, resultf));
      this.onloadj(cell, cell.getAttribute("onloadj"));

   }
   this.replacefld = function(newTR, resultf)
   {
      if(newTR.nodeType == 3)return;
      if(newTR.getAttribute("jvc.dataurl"))return;

      for(var j = 0; j < newTR.childNodes.length;
      j ++ )
      {
         var cell = newTR.childNodes[j];
         this.replaceCell(cell, resultf);
         this.replacefld(cell, resultf);
      }
   }

}

function replacehref(shref, resultf, row)
{
   var fields = [];
   for(var fld in resultf) fields[fields.length] = fld ;
   
   for(var i = 0; i < fields.length; i ++ )
   {
      shref = shref.replace(new RegExp("@" + fields[i], "gi"), resultf[fields[i]]);
      
   }
   if(row)shref = shref.replace(new RegExp("@numrow", "gi"), row);

   return shref;

}

function format(str, fmt)
{
   if( ! str || ! fmt)return "";
   if(str == "" || fmt == "")return "";
   if(fmt.indexOf("len:") == 0)return formatLen(str, fmt.replace(new RegExp("len:", "gi"), ""));
   if(fmt.indexOf("len2:") == 0)return formatLen2(str, fmt.replace(new RegExp("len2:", "gi"), ""));
   var value = str;
   if(fmt.indexOf("eval:") == 0)
   {
      return eval(fmt.replace(new RegExp("eval:", "gi"), ""));
   }

   return (formatDate(parseDate(str), fmt));
}
function formatLen(str, len)
{
   if(str.length <= len)return str;
   return str.substring(0, len);
}
function formatLen2(str, len)
{
   if(str.length <= len)return str;
   return str.substring(0, len)+"...";
}

function parseDate(str)
{
   if(typeof str == 'string')
   {
      results = str.match(/^ *(\d{1,2}):(\d{1,2}):(\d{1,2}) *$/);
      if(results && results.length > 3)
      return new Date(1900,0,1, parseInt2(results[1]), parseInt2(results[2]), parseInt2(results[3]));
      var results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) *$/);
      if(results && results.length > 3)
      return new Date(parseInt2(results[1]), parseInt2(results[2]) - 1, parseInt2(results[3]));
      results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2}) *$/);
      if(results && results.length > 6)
      return new Date(parseInt2(results[1]), parseInt2(results[2]) - 1, parseInt2(results[3]), parseInt2(results[4]), parseInt2(results[5]), parseInt2(results[6]));
      results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2})\.(\d{1,9}) *$/);
      if(results && results.length > 7)
      return new Date(parseInt2(results[1]), parseInt2(results[2]) - 1, parseInt2(results[3]), parseInt2(results[4]), parseInt2(results[5]), parseInt2(results[6]), parseInt2(results[7]));
   }
   return null;
}

function decimal(num, v)
{
   var vv = Math.pow(10, v);
   return Math.round(num * vv) / vv;
}

function parseInt2(str)
{
   var v = str;
   while(v.indexOf(0) == 0 && v.length > 0)v = v.substring(1, v.length);
   if(v == '')v = 0;
   return parseInt(v);
}
function formatDate(v)
{
   if(typeof v == 'string') v = parseDate(v);
   if(v instanceof Date)
   {
      var y = v.getFullYear();
      var m = v.getMonth() + 1;
      var d = v.getDate();
      var h = v.getHours();
      var i = v.getMinutes();
      var s = v.getSeconds();
      var ms = v.getMilliseconds();
      if(ms > 0) return y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s + '.' + ms;
      if(h > 0 || i > 0 || s > 0) return y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s;
      return y + '-' + m + '-' + d;
   }
   return '';
}


function formatDate(dt, cdti)
{
   if(cdti !== undefined)
   {
      return cdti.replace(/(yyyy|yy|MM|dd|HH|mm|ss|ms|wd)/ig, function($1)
      {
         switch($1)
         {
            case 'yyyy' :
               return dt.getFullYear();
            case 'yy' :
               {
                  var yy = dt.getFullYear() % 100;
                  if(yy < 10)yy = '0' + yy;
                  return yy
               }
               ;
            case 'MM' :
               return padNum(dt.getMonth() + 1, 0, 2);
            case 'dd' :
               return padNum(dt.getDate(), 0, 2);
            case 'HH' :
               return padNum(dt.getHours(), 0, 2);
            case 'mm' :
               return padNum(dt.getMinutes(), 0, 2);
            case 'ss' :
               return padNum(dt.getSeconds(), 0, 2);
            case 'ms' :
               return padNum(dt.getMilliseconds(), 0, 3);
            case 'wd' :
               return week(dt.getDay());
         }
      }
      )
   }
   else
   {
      return dt.getFullYear() + '-' + padNum(dt.getMonth() + 1, 0, 2) +
      '-' + padNum(dt.getDate(), 0, 2);
   }
   function week(day)
   {
      switch(day)
      {
         case 0 :
         day = '日';
         break;
         case 1 :
         day = '一';
         break;
         case 2 :
         day = '二';
         break;
         case 3 :
         day = '三';
         break;
         case 4 :
         day = '四';
         break;
         case 5 :
         day = '五';
         break;
         case 6 :
         day = '六';
         break;
      }
      return day;
   }
   function padNum(str, num, len)
   {
      var temp = ''
      for(var i = 0; i < len; temp += num, i ++ );
      return temp = (temp += str).substr(temp.length - len);
   }

}

function autoTypeValue(v)
{
   var intParten = /^[-\+]?\d+$/;
   var dblParten = /^[-\+]?\d+(\.\d+)?$/;

   if(  intParten.test(v))return parseInt(v);
   if(  dblParten.test(v))return parseFloat(v);

   return v;
}


var jvc_data_setclass = function(obj, c)
{
   return function()
   {
      obj.className = c;
   }
}


function jvc_data_page()
{
   
   
   	
   this.set = function (result, name, listDiv, oDiv, jsSrc)
   {
      if( ! oDiv)return;
      this.pageDiv = oDiv;
      this.listDiv = listDiv;
      oDiv.innerHTML = "";
      oDiv.style.fontSize = "12px";
      oDiv.style.Color = "#444";
      oDiv.me = this;
      this.name = name;
      this.page = oDiv;
      this.jsSrc = jsSrc;
    
      if(result[name + ".page"])
      this.pageinfo = result[name + ".page"][0];
      else if(result[name + "_page"])
      this.pageinfo = result[name + "_page"];
      else return;

      var strPage = "";
      // 首页
      if (this.pageinfo.CurPage > 2)
      {
         strPage += "<img style='cursor:pointer' src='"+jvc.baseUrl + "jvc/data.files/firs_button.gif' onclick='$$(\""+oDiv.id+"\").me.loaddata(1)'> ";
      }
      // 上一页
      if (this.pageinfo.CurPage > 1)
      {
         strPage += "<img style='cursor:pointer' src='"+jvc.baseUrl + "jvc/data.files/prev_button.gif' onclick='$$(\""+oDiv.id+"\").me.loaddata("+(this.pageinfo.CurPage-1)+")'> ";
      }
      // 下一页
      if (this.pageinfo.CurPage < this.pageinfo.TotalPageCount)
      {
         strPage += "<img style='cursor:pointer' src='"+jvc.baseUrl + "jvc/data.files/next_button.gif'  onclick='$$(\""+oDiv.id+"\").me.loaddata("+(this.pageinfo.CurPage+1)+")'> ";
      }
      // 末页
      if (this.pageinfo.CurPage < this.pageinfo.TotalPageCount - 1)
      {
         strPage += "<img style='cursor:pointer' src='"+jvc.baseUrl + "jvc/data.files/last_button.gif'  onclick='$$(\""+oDiv.id+"\").me.loaddata("+(this.pageinfo.TotalPageCount)+")'> ";
      }
      strPage += "共" + this.pageinfo.RecordsCount + "条记录 分" + this.pageinfo.TotalPageCount + "页 每页<input style='width:30px' value='" + this.pageinfo.RecordsPerPage + "' onkeyup=\"this.value=this.value.replace(/[^\\d]/g,'')\" onblur='if(this.value>999)this.value=999;$$(\""+oDiv.id+"\").me.loadsize(this.value)'/>条 ";
      strPage += "当前第<select onchange='$$(\""+oDiv.id+"\").me.loaddata(this.value)'>";
      var showPageCount=10;
      var iStart=this.pageinfo.CurPage-showPageCount;
	  if(iStart<1)iStart=1;
	  var iEnd=iStart+2*showPageCount;
	  if(iEnd>this.pageinfo.TotalPageCount)iEnd=this.pageinfo.TotalPageCount;
      
      
      for (var i = iStart; i <= iEnd;
      i ++ )
      {
         strPage += "<option ";
         if(i == this.pageinfo.CurPage)strPage += "selected";
         strPage += " value=" + i + " >" + i + "</option>";
      }
      strPage += "</select>页";
      this.curpage = this.pageinfo.CurPage;
      oDiv.innerHTML = strPage;
   }
   this.reload=function(){
   		this.loaddata( this.curpage);
   }	
   this.loadsize=function(recordsperpage){
   	  if( this.pageinfo.RecordsPerPage==recordsperpage)return;
   	  if(isNaN(recordsperpage))return;
   	  if(recordsperpage==0)return;
   	  if(recordsperpage>999)return;
      var src = this.jsSrc + "&" + this.name + ".recordsperpage=" + recordsperpage;   		
      new jvc_json().query(src, json_callback, this.name, this.listDiv, this.pageDiv, this.jsSrc);
   }
   this.loaddata = function(CurPage)
   {
   		if(this.listDiv.isQuery=="1")return;
   		this.listDiv.isQuery="1";
   		if(!this.listDiv.isGrid)jvc.data.appendNodeMessage(this.listDiv,"<nobr>&nbsp;&nbsp;查询中,请稍候...</nobr>");
      var src = this.jsSrc + "&" + this.name + ".CurPage=" + CurPage+"&"+ this.name + ".recordsperpage=" + this.pageinfo.RecordsPerPage;   		
      new jvc_json().query(src, json_callback, this.name, this.listDiv, this.pageDiv, this.jsSrc);
   }

}


(function()
{
   if( ! window.Connection )
   window.Connection =
   {
   }
   ;
   window.Connection.loadCallback = (function()
   {
      /*
      * param参数说明
      * @param { Object } param 包括如下属性
      * name - {String} (可选)从服务器返回的callback函数名称
      * key - {String} (可选)传递给服务器的callback函数的参数名，例如xxxx ? key = callbackFunction，默认值为"callback"
      * url - {String} (必填)请求的URL
      * success - {Function} (必填)请求成功后的处理函数
      * error - {Function}(选填)请求失败后的处理函数
      */
      /* 根据规则处理用户参数 */
      function initParam( param )
      {
         /* 如果未指定callback函数，则表示是可以通过URL中的参数来传递callback函数名的，在此自动生成一个callback函数并作为query string加到URL之后 */
         if( ! param.name )
         {
            param.name = '_callback_func_' + ( + new Date());
         }
         /* 如果未指定query string中表示callback函数名的参数则默认为callback */
         if( ! param.key )
         {
            param.key = 'callback';
         }
         /* 重构URL */
         var url = param.url;
         var index = url.indexOf('?');
         if( index < 0 )
         {
            param.url += '?' + param.key + '=' + param.name;
         }
         else
         {
            /* 查找query string中是否已经包含了名为param.key的参数名，如果已经包含则忽略 */
            var queryString = url.substring(index + 1);
            var existed = false;
            var pairs = queryString.split('&');
            for( var i = 0, len = pairs.length; i < len;
            i ++ )
            {
               var p = pairs[i];
               if( p.split('=')[0] == param.key )
               {
                  existed = true;
                  break;
               }
            }
            if( ! existed )
            {
               param.url += '&' + param.key + '=' + param.name;
            }
         }

         return param;
      }

      /* IE */
      function loadIECallback(param)
      {
         param = initParam(param);
         /* 清除，防止内存泄露 */
         function clear()
         {
            frag = script = script.onreadystatechange = frag[param.name] = null;
         }
         var charset = param.charset || 'gb2312';
         /* 创建一个DocumentFragment充当script元素的父容器，这样的好处是不需要将节点真正的加入到DOM树中 */
         var frag = document.createDocumentFragment(), script = document.createElement('script');
         script.charset = charset;
         /* 将callback函数定义在DocumentFragment上，script返回后可以直接调用到该函数 */
         frag[param.name] = function ()
         {
            /* 调用用户传入的callback */
            var args = [];
            args[0] = arguments[0];
            args[1] = param.p1;
            args[2] = param.p2;
            args[3] = param.p3;
            args[4] = param.p4;
            param.success && param.success.apply(null, args);
            /* 使用完成后清除垃圾信息 */
            clear();
         }
         ;
         /* 注册script的onreadystatechange事件
         * 一般情况，IE6下script的readyState会经历loading、interactive和loaded，
         * IE7下没有interactive(表示加载的数据虽然未完成但已经可以使用)状态，
         * 而在interactive(IE7下则是loading之后和loaded之前)状态后请求的callback数据其实已经到达并可用
         * 也就是说如果正常请求到数据，则在loaded状态前定义在DocumentFragment上的Callback就会被执行。
         * 由于加载成功后onreadystatechange事件会被清空，因此一旦readyState到达了loaded状态则表示加载错误。
         */
         script.onreadystatechange = function ()
         {
            if (script.readyState == 'loaded')
            {
               param.error && param.error();
               clear();
            }
         }
         ;
         script.src = param.url;
         frag.appendChild(script);
      }

      /* 其他浏览器 */
      function loadOther(param)
      {
         param = initParam(param);
         /* 清除，防止内存泄露 */
         function clear()
         {
            iframe.callback = iframe.errorcallback = null;
            iframe.src = 'about:blank', iframe.parentNode.removeChild(iframe), iframe = null;
         }
         var charset = param.charset || 'gb2312';
         /* 采用iframe可以对错误进行响应 */
         var iframe = document.createElement('iframe');
         iframe.style.display = 'none';

         /* 在iframe的frameElement上定义callback */
         iframe.callback = function ()
         {
         	 var args = [];
            args[0] = arguments[0];
            args[1] = param.p1;
            args[2] = param.p2;
            args[3] = param.p3;
            args[4] = param.p4;
           
            param.success && param.success.apply(null, args);
            clear();
         }
         ;
         iframe.errorcallback = function ()
         {
            param.error && param.error();
            clear();
         }
         ;
         try
         {
            document.body.appendChild(iframe);
            var doc = iframe.contentWindow.document;
            	 var args = [];
            	 
            
            arguments[1] = param.p1;
            arguments[2] = param.p2;
            arguments[3] = param.p3;
            arguments[4] = param.p4;
            doc.open();
            doc.write(
            /* 在iframe内容中定义真是的callback函数，以供正确请求到数据后进行响应，如果正确地请求到数据则会执行success回调并删除对错误的响应函数 */
            '<script type="text\/javascript">function ' + param.name + '() {  window.frameElement.callback.apply(null, arguments);}<\/script>'
            /* 写入script标签请求数据 */
            + '<script type="text\/javascript" src="' + param.url + '" charset="' + charset + '"><\/script>'
            /* 如果没有请求道正确的数据，则会顺利执行完下面的脚步片段，对错误进行响应 */
            + '<script type="text\/javascript">window.setTimeout("try { window.frameElement.errorcallback(); } catch (exp) {}", 1)<\/script>'
            );
            doc.close();
         }
         catch (exp)
         {
         	alert(exp);
         }
      }
      if(/ MSIE 10/ .test(window.navigator.userAgent))return loadOther;
      return / MSIE / .test(window.navigator.userAgent) ? loadIECallback : loadOther;
   }
   )();
}
)();

function jvc_json()
{
   this.index = 0;
   this.remotequery = function(jsSrc, callback, p1, p2, p3, p4,p5)
   {
      jsSrc += "&jvcram_temp=" + Math.random();
      this.query(jvc.remoteserver + jsSrc, callback, p1, p2, p3, p4,p5);
   }
   this.docallback = function(callback, j, p1, p2, p3, p4,p5)
   {
      if( ! callback)return;
      if (p5)
      {
         callback(j, p1, p2, p3, p4,p5);
         return;
      }

      if (p4)
      {
         callback(j, p1, p2, p3, p4);
         return;
      }
      if (p3)
      {
         callback(j, p1, p2, p3   );
         return;
      }
      if (p2)
      {
         callback(j, p1, p2      );
         return;
      }
      if (p1)
      {
         callback(j, p1         );
         return;
      }
      callback(j);
   }


   this.querytest = function(jsSrc, callback, p1, p2, p3, p4,p5)
   {

      Connection.loadCallback(
      {
         name : 'test',
         url : jsSrc,
         success : callback,
         error : callback,
         p1 : p1, p2 : p2, p3 : p3, p4 : p4,p5:p5
      }
      );
   }
   this.query = function(jsSrc, callback, p1, p2, p3, p4,p5)
   { 
      // alert(jsSrc);
      Connection.loadCallback(
      {
         url : jsSrc,
         success : callback,
         error : callback,
         p1 : p1, p2 : p2, p3 : p3, p4 : p4,p5:p5
      }
      );

   }

   this.remotesubmit = function(theForm, callback, p1, p2, p3, p4,p5)
   {
      this.remotequery(this.buildQueryString(theForm), callback, p1, p2, p3, p4,p5);
   }

   this.submit = function(theForm, callback, p1, p2, p3, p4,p5)
   {
      this.query(this.buildQueryString(theForm), callback, p1, p2, p3, p4,p5);
   }
   this.encodeParam = function(str)
   {

      if(jvc.localmode)return escape(str);
      return encodeURIComponent(str);
   }
   this.format = function(str, fmt)
   {
      if( ! str || ! fmt)return "";
      if(str == "" || fmt == "")return "";
      if(fmt.indexOf("len:") == 0)return formatLen(str, fmt.replace(new RegExp("len:", "gm"), ""));
      if(fmt.indexOf("eval:") == 0)
      {
         return eval("var value='"+str+"';" + fmt.replace(new RegExp("eval:", "gm"), ""));
      }
      return "";
   }
   this.buildQueryString = function(theForm)
   {
      var url = "";
      if(theForm.getAttribute("json")) url = theForm.getAttribute("json");
      if(theForm.json) url = theForm.json;


      for(var i = 0; i < theForm.elements.length; i ++ )
      {
         if(theForm.elements[i].name == "")continue;

         if(theForm.elements[i].type == "checkbox")
         {
            var value0 = theForm.elements[i].getAttribute("value0");
            if( ! theForm.elements[i].checked && typeof(value0) == 'undefined')continue;
            if(theForm.elements[i].value == "")continue;
            if(url.indexOf("?") >= 0)url += "&";
            else url += "?";
            url += this.encodeParam(theForm.elements[i].name);
            url += "=";
            if(theForm.elements[i].checked)url += this.encodeParam(theForm.elements[i].value);
            else url += this.encodeParam(value0);



         }
         else if(theForm.elements[i].type == "radio")
         {

            // 						 alert(theForm.elements[i].checked + "|" + theForm.elements[i].value);
            if(theForm.elements[i].checked)
            {
               if(url.indexOf("?") >= 0)url += "&";
               else url += "?";
               url += this.encodeParam(theForm.elements[i].name);
               url += "=";
               url += this.encodeParam(theForm.elements[i].value);
            }
         }
         else
         {
            if(url.indexOf("?") >= 0)url += "&";
            else url += "?";
            url += this.encodeParam(theForm.elements[i].name);
            url += "=";
            var value = theForm.elements[i].value;
            if(theForm.elements[i].getAttribute("unfmt"))value = this.format(theForm.elements[i].value, theForm.elements[i].getAttribute("unfmt"));
            url += this.encodeParam(value);
         }

      }
      if(url.indexOf("?") >= 0)url += "&jvc.encoding=utf-8";
      else url += "?jvc.encoding=utf-8";
      return url;
   }
   ;
}


function json_callback(j, name, listDiv, pageDiv, jsrc)
{
  listDiv.isQuery="0";	
   new jvc_data().setList(listDiv, j, name);
   new jvc_data_page().set(j, name, listDiv, pageDiv, jsrc);
   if(listDiv.tagName=="TBODY")ts_makeSortable(listDiv);
 }


var SORT_COLUMN_INDEX;

function ts_makeSortable(tbody) {
    var table=tbody.parentNode;
    if (table.rows && table.rows.length > 0) {
        var firstRow = table.rows[0];
    }
    if (!firstRow) return;
    
    // We have a first row: assume it's the header, and make its contents clickable links
    for (var i=0;i<firstRow.cells.length;i++) {
        var cell = firstRow.cells[i];
        var txt = ts_getInnerText(cell);
		if(txt==cell.innerHTML){
	    if(i==0 && false)
		 cell.innerHTML = '<b href="#" class="sortheader" '+ 'onclick="ts_resortTable(this, '+i+');return false;">' + txt+'<span class="sortarrow"></span></b>';
		else{
	    cell.innerHTML = '<b href=#>'+txt+'</b><span class="sortarrow"></span>';
		cell.tag=i;
        
		cell.ondblclick=function(){
			ts_resortTable(this, this.tag,tbody);
		}}
		}
    }
}

function ts_getInnerText(el) {
	if (typeof el == "string") return el;
	if (typeof el == "undefined") { return el };
	if (el.innerText) return el.innerText;	//Not needed but it is faster
	var str = "";
	
	var cs = el.childNodes;
	var l = cs.length;
	for (var i = 0; i < l; i++) {
		switch (cs[i].nodeType) {
			case 1: //ELEMENT_NODE
				str += ts_getInnerText(cs[i]);
				break;
			case 3:	//TEXT_NODE
				str += cs[i].nodeValue;
				break;
		}
	}
	return str;
}

function ts_resortTable(lnk,clid,tbody) {
    
    // get the span
    var span;
    for (var ci=0;ci<lnk.childNodes.length;ci++) {
        if (lnk.childNodes[ci].tagName && lnk.childNodes[ci].tagName.toLowerCase() == 'span') span = lnk.childNodes[ci];
    }
    var spantext = ts_getInnerText(span);
    var td = lnk.parentNode;
    var column = clid || td.cellIndex;
    if(isNaN(column))column=0;
    var table = getParent(td,'TABLE');
    
    // Work out a type for the column
    if (table.rows.length <= 1) return;
    var itm = ts_getInnerText(table.rows[1].cells[column]);
    sortfn = ts_sort_caseinsensitive;
    if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/)) sortfn = ts_sort_date;
    if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/)) sortfn = ts_sort_date;
    if (itm.match(/^[$]/)) sortfn = ts_sort_currency;
    if (itm.match(/^[\d\.]+$/)) sortfn = ts_sort_numeric;
    if (itm.match(/^[\/-][\d\.]+$/)) sortfn = ts_sort_numeric;
    SORT_COLUMN_INDEX = column;
    var firstRow = new Array();
    var newRows = new Array();
    var nextCount=0;
    for (j=1;j<tbody.rows.length;j++){
        if(tbody.rows[j].style && tbody.rows[j].style.display=="none")nextCount++;
    
    }
    for (i=0;i<tbody.rows[0].length;i++) { firstRow[i] = tbody.rows[0][i]; }
    for (j=1;j<tbody.rows.length-nextCount;j++) {
    //if(tbody.rows[j+nextCount].className=='footer')break;
     newRows[j-1] = tbody.rows[j+nextCount]; 

}

    newRows.sort(sortfn);

    if (span.getAttribute("sortdir") == 'down') {
        ARROW = '&uarr;';
        newRows.reverse();
        span.setAttribute('sortdir','up');
    } else {
        ARROW = '&darr;';
        span.setAttribute('sortdir','down');
    }
    
    // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
    // don't do sortbottom rows
    for (i=0;i<newRows.length;i++) {
     var newTR=newRows[i];
         if(i % 2==1){
                        newTR.className="list_two";
                        jvc.attachEvent(newTR, "mouseout", jvc_data_setclass(newTR, 'list_two'));
                    }else{
                        newTR.className="list_one";
                        jvc.attachEvent(newTR, "mouseout", jvc_data_setclass(newTR, 'list_one'));
                    }
 if (!newRows[i].className || (newRows[i].className && (newRows[i].className.indexOf('sortbottom') == -1))) tbody.appendChild(newRows[i]);}
    // do sortbottom rows only
    for (i=0;i<newRows.length;i++) { if (newRows[i].className && (newRows[i].className.indexOf('sortbottom') != -1)) tbody[0].appendChild(newRows[i]);}
    
    // Delete any other arrows there may be showing
    var allspans = document.getElementsByTagName("span");
    for (var ci=0;ci<allspans.length;ci++) {
        if (allspans[ci].className == 'sortarrow') {
            if (getParent(allspans[ci],"table") == getParent(lnk,"table")) { // in the same table as us?
                allspans[ci].innerHTML = '';
            }
        }
    }
        
    span.innerHTML = ARROW;
}

function getParent(el, pTagName) {
	if (el == null) return null;
	else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())	// Gecko bug, supposed to be uppercase
		return el;
	else
		return getParent(el.parentNode, pTagName);
}
function ts_sort_date(a,b) {
    // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
    if (aa.length == 10) {
        dt1 = aa.substr(6,4)+aa.substr(3,2)+aa.substr(0,2);
    } else {
        yr = aa.substr(6,2);
        if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
        dt1 = yr+aa.substr(3,2)+aa.substr(0,2);
    }
    if (bb.length == 10) {
        dt2 = bb.substr(6,4)+bb.substr(3,2)+bb.substr(0,2);
    } else {
        yr = bb.substr(6,2);
        if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
        dt2 = yr+bb.substr(3,2)+bb.substr(0,2);
    }
    if (dt1==dt2) return 0;
    if (dt1<dt2) return -1;
    return 1;
}

function ts_sort_currency(a,b) { 
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    return parseFloat(aa) - parseFloat(bb);
}

function ts_sort_numeric(a,b) { 
    aa = parseFloat(ts_getInnerText(a.cells[SORT_COLUMN_INDEX]));
    if (isNaN(aa)) aa = 0;
    bb = parseFloat(ts_getInnerText(b.cells[SORT_COLUMN_INDEX])); 
    if (isNaN(bb)) bb = 0;
    return aa-bb;
}

function ts_sort_caseinsensitive(a,b) {
    try{
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;
    }catch(err){return 0;}
}

function ts_sort_default(a,b) {
    try{
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]); 
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;
    }catch(err){return 0;}
}
